import { history } from 'umi';
import { getKeyRouter } from '@/utils';
import { getSourceManageTableColumns, getSourceManageSearchColumns, getSourceManageTableHeaderActions } from '../mconfig/index';
import { SourceManageService, getPackService } from '../services/ManageService';
import { ManageCommonAPI } from '@/pages/type';
import { useState } from 'react';
import { formatDecimal } from '../../Acommon';
import { findSourceFailureBidSev } from '../services/UpdateService';
import { message } from 'antd';

export function useSourceManage(curRes, locationProps) {
  /** 实施管理页数据 */
  const { SourceRun, SourceData, setDataSource, SourceLoading, SourceTableProps, requestManage } = SourceManageService(curRes, locationProps);

  /**实施-【流标】数据集合接口*/
  const { findSourceFailureBidRun, findSourceFailureBidLoading } = findSourceFailureBidSev();

  /** 保存表格展开行的key值 */
  const [tableExpantKeys, setTableExpantKeys] = useState<string[]>([]);

  /** 保存展开的key */
  const [tableExpandKey, setTableExpandKey] = useState<string>('');

  /**抽屉的显示*/
  const [open, setOpen] = useState<Record<string, any>>({});

  /** 是否显示公告 */
  const [isShowAnnoun, setIsShowAnnoun] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
  });

  /* 是否展示弹框 */
  const [isShowModal, setIsShowModal] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
  });

  /** 是否展示抽屉 */
  const [isShowDrawer, setIsShowDrawer] = useState<Record<string, any>>({
    isShow: false,
    resObj: {},
  });

  const { getPackRun, getPackLoading } = getPackService();

  /**
   * @operation
   * @description 管理页操作事件
   */
  const operation = {
    onEdit: (record: Record<string, any>) => {
      history.push({
        pathname: `/purchaseSourceController/addBid/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'edit',
          info: record,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onOpenDrawer: (record) => {
      setOpen({ isShow: true, resObj: record });
    },
    // onView: (resObj: Record<string, any>) => {
    //   history.push({
    //     pathname: `/purchaseSourceController/getSourceById/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
    //     state: {
    //       type: 'detail',
    //       info: resObj,
    //     },
    //   });
    // },
    onViewPage: (resObj: Record<string, any>) => {
      history.push({
        pathname: `/purchaseSourceController/getBidById/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'detail',
          info: resObj,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onClarify: (resObj: Record<string, any>) => {
      history.push({
        pathname: `/purchaseSourceClarifyController/add/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'clarify',
          info: resObj,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onSupplier: (resObj: Record<string, any>) => {
      history.push({
        pathname: `/purchaseSourceSupplierController/add/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'supplier',
          info: resObj,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onCalibrate: (resObj: Record<string, any>) => {
      history.push({
        pathname: `/purchaseSourceCalibrateController/addSourceCalibrate/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'calibrate',
          info: resObj,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    // 流标-公告
    onAnnoun: (resObj: Record<string, any>) => {
      setIsShowAnnoun({
        isShow: true,
        resObj,
      });
    },
    // 流标-变更
    onChangeMethod: (resObj) => {
      let {
        projectCode,
        projectFlag,
        projectID,
        projectName,

        applyID,
        applyTitle,
        applyDepartmentID,
        applyDepartmentName,

        id,
        procureReal,
        packName,
        packID,
        expectSum,
        procureOrg,
      } = resObj;

      let params = {
        projectCode,
        projectFlag,
        projectID,
        projectName,
        applyTitle,
        applyDepartmentID,
        applyDepartmentName,
        packName,
        packID,
        expectSum: formatDecimal(expectSum),
        applyID,
        changeID: null,
        procureDraft: procureReal,
        sourceID: id,
        procureOrg,
      };

      history.push({
        pathname: `/purchaseSourceChangeController/add/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          info: params,
          operateType: 'add',
          sourcePage: 'source',
          returnPathName: locationProps?.pathname,
          // localUrl: '/sourceController/manage',
          // delRouterName: history?.location?.pathname,
        },
      });
    },
    // // 打开新的弹框
    // onOpen: () => {
    //   setIsShowModal({
    //     isShow: true,
    //     resObj: {},
    //   });
    // },
    // 打开抽屉
    onShowDrawer: (resObj) => {
      getPackRun({ packIds: resObj.packID }).then((res) => {
        if (res?.msgFlag) {
          setIsShowDrawer({
            isShow: true,
            resObj: res?.obj[0],
          });
        }
      });
    },
  };

  /**
   * @searchOperation
   * @description 搜索列表事件
   */
  const searchOperation = {
    onOpen: (record: Record<string, any>) => setIsShowModal({ isShow: record, resObj: {} }),
  };
  /**  重置搜索表单方法 */
  const onReset = (values: any) => {
    requestManage({ ...values });
    setTableExpantKeys([]);
  };

  /**  搜索列表 */
  const onSearch = (request: ManageCommonAPI.IGridRequestType) => {
    requestManage({ ...request });
    setTableExpantKeys([]);
  };

  /**分页方法*/
  const onPageChange = (current: any, pageSize: any, params: any) => {
    requestManage({ pageSize, current, ...params });
    setTableExpantKeys([]);
  };

  /**设置源数据的children*/
  const setSourceDataFun = (id, childList) => {
    let dataList: Record<string, any>[] = [];
    SourceData?.forEach((item: any) => {
      dataList?.push({
        ...item,
        children: item?.id == id ? childList : item?.children,
      });
    });
    setDataSource(dataList);
  };

  /**请求流标列表接口-处理实施数据*/
  const getSourceFailureBidFun = async (obj) => {
    const result = await findSourceFailureBidRun(obj);
    if (result?.msgFlag) {
      message?.success(result?.msg);
      handleTableExpant(true, obj?.id);
      SourceData?.forEach((item: any) => {
        if (item?.id === obj?.id) {
          let arr = result?.obj;
          arr.forEach((items) => {
            items.pID = obj?.id;
          });
          item.children = arr;
        }
      });
      setDataSource(SourceData);
    }
  };

  /** 处理展开的表格key值 */
  const handleTableExpant = (open: boolean, clickKey: string) => {
    let openKeys: string[] = [...tableExpantKeys];
    if (open) {
      openKeys?.push(clickKey);
    } else {
      openKeys = tableExpantKeys?.filter((item: any) => item != clickKey);
    }
    setTableExpantKeys(openKeys);
  };

  const tableProps: any = {
    columns: getSourceManageTableColumns(operation, curRes),
    dataSource: SourceData,
    loading: SourceLoading || findSourceFailureBidLoading || getPackLoading,
    pagination: SourceTableProps?.pagination,
    rowKey: 'id',
    onPageChange: onPageChange,
    expandable: {
      onExpand: (expanded: boolean, record: Record<string, any>) => {
        if (expanded) {
          setTableExpandKey(record?.id);
          getSourceFailureBidFun({ id: record?.id });
        } else {
          setSourceDataFun(record?.id, []);
          handleTableExpant(false, record?.id);
        }
      },
      expandedRowKeys: tableExpantKeys,
    },
  };

  const searchProps: any = {
    switchList: [],
    onSwitch: () => {},
    searchList: getSourceManageSearchColumns(searchOperation),
    onSearch: onSearch,
    onReset: onReset,
  };

  const actionList = getSourceManageTableHeaderActions(operation);

  return {
    open,
    operation,
    tableProps,
    searchProps,
    actionList,
    isShowAnnoun,
    isShowModal,
    setOpen,
    setIsShowModal,
    isShowDrawer,
    setIsShowDrawer,
    setIsShowAnnoun,
    requestManage,
  };
}
